import 'dart:async';
import 'dart:io';

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:mobile_app/app/infrastructure/services/flavor_service/service.dart';
import 'package:mobile_app/app/presentation/widget/widget.dart';
import 'package:mobile_app/injection_container.dart' as di;
import 'package:mobile_app.core/core/domain/config/config.dart' hide Platform;
import 'package:mobile_app.core/crashlytics/crashlytics.dart';
import 'package:mobile_app.core/logger/logger.dart';

Future<void> main() async {
  final widgetsBinding = WidgetsFlutterBinding.ensureInitialized();

  FlutterNativeSplash.preserve(
    widgetsBinding: widgetsBinding,
  );

  await Future.wait([
    () async {
      final flavor = await const FlavorService().getFlavor();

      if (Platform.isIOS) {
        if (flavor == 'prod') {
          await Config().initProd(
            applicationStore: ApplicationStore.appStore,
          );
        } else if (flavor == 'dev') {
          await Config().initDev(
            applicationStore: ApplicationStore.appStore,
          );
        }
      } else if (Platform.isAndroid) {
        if (flavor == 'prod') {
          await Config().initProd(
            applicationStore: ApplicationStore.googlePlay,
          );
        } else if (flavor == 'dev') {
          await Config().initDev(
            applicationStore: ApplicationStore.googlePlay,
          );
        }
      }
    }(),
    Firebase.initializeApp(),
  ]);

  Logger.logLevel = Config().logLevel;

  await Crashlytics().initialize();

  FlutterError.onError = Crashlytics().recordFlutterFatalError;

  PlatformDispatcher.instance.onError = (error, stackTrace) {
    Crashlytics().recordError(
      error: error,
      stackTrace: stackTrace,
      fatal: true,
    );

    return true;
  };

  await Future.wait([
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]),
    di.init(),
  ]);

  runApp(const AppWidget());
}
